package com.yc.litemonitoringserver.server;

import com.yc.api.HostInfo;
import com.yc.db.DbUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.commons.dbutils.QueryRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class LiteMonitoringServerHandler extends SimpleChannelInboundHandler<Object> {
    private static final Logger logger =
            LoggerFactory.getLogger(LiteMonitoringServerHandler.class);

    private static final String SQL_INSERT =
            "INSERT INTO t_host_info (host, create_time, used_memory, "
                    + "total_memory, used_cpu) VALUES (?, ?, ?, ?, ?)";

    //当采集客户端与采集服务端建立连接时，触发该方法，将接收到的主机信息保存到数据库中
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object obj) throws Exception {

        if (obj instanceof HostInfo) {
            HostInfo hostInfo = (HostInfo) obj;
            String host = ctx.channel().remoteAddress().toString().replace("/","");  //获取客户端地址
            hostInfo.setHost(host);

            logger.info("client {}  -> Server: {}" , hostInfo.getHost(), hostInfo);

            QueryRunner run = new QueryRunner(DbUtil.getDataSource());

            // 创建
            int inserts = run.update(SQL_INSERT, hostInfo.getHost(),
                    hostInfo.getCreateTime(), hostInfo.getUsedMemory(),
                    hostInfo.getTotalMemory(), hostInfo.getUsedCpu());
            logger.info("Insert Results：{}" ,inserts);
        }
    }

}
